import pandas as pd

data = [1, 2, 3, 4, 5, 6]
index = ["a", "b", "c", "d", "e", "f"]
series = pd.Series(data, index=index, name="A")

# 1.遍历
# 1.1 for循环遍历
for value in series:
    print(value)

# 1.2 iter遍历 --NG
# for ind, value in iter(series()):
#     print(f"{ind}: {value}")

# 1.3 enumerate遍历
for ind, value in enumerate(series):
    print(f"{ind}: {value}")

# 2.lamba 求和,求平方和
sum = series.sum()  # 求和
sum_square = series.apply(lambda x: x**2).sum()  # 求平方和
sum_square2 = (series **2).sum()  # 求平方和 方法2
print("sum: ", sum)
print("sum_square: ", sum_square)
print("sum_square2: ", sum_square2)

# 3.求平方和 apply性能测试
import timeit

t1 = timeit.timeit(
    """
import pandas as pd
series = pd.Series([1, 2, 3, 4, 5, 6])
sum_square = series.apply(lambda x: x**2).sum()
""",
    number=10000,
)

t2 = timeit.timeit(
    """
import pandas as pd
series = pd.Series([1, 2, 3, 4, 5, 6])
sum_square2 = (series**2).sum()
""",
    number=10000,
)

print("t1: ", t1)
print("t2: ", t2)
""" 
t1:  1.8916908370001693
t2:  2.026673319999645
"""
# 结论: apply的性能更高
